//
//  SDP_ViewForAVPlayerWithUrl.m
//  SDP_AVMoviePlayer
//
//  Created by sp on 16/3/25.
//  Copyright © 2016年 sp. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>

#import "SDP_ViewForAVPlayerWithUrl.h"

#import "SDP_ActivityIndicatorView.h"

#import "EveryDayModel.h"

#import "KSBarrageView.h"
// 枚举值，包含水平移动方向和垂直移动方向
typedef NS_ENUM(NSInteger, PanDirection){
    PanDirectionHorizontalMoved,
    PanDirectionVerticalMoved
};



#define WIDTH  [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

@interface SDP_ViewForAVPlayerWithUrl ()


{
    PanDirection panDirection; // 定义一个实例变量，保存枚举值
    BOOL isVolume; // 判断是否正在滑动音量
    CGFloat sumTime; // 用来保存快进的总时长
}


//@property (nonatomic, strong)AVPlayer *moviePlayer;
//@property (nonatomic, strong)AVPlayerItem *moviePlayerItem;
@property (nonatomic, strong)AVPlayerLayer *moviePlayerLayer;

// 保存该视频资源的总时长，快进或快退的时候要用
@property (nonatomic, assign) CGFloat totalMovieDuration;
@property(nonatomic,assign)BOOL isPlay;
/** 底部的滑动条下的 view */
@property (nonatomic, strong) UIView *sliderView;
@property (nonatomic, strong) UISlider *sliderForMovie;
@property (nonatomic, strong) UISlider *sliderForVoice;

/** 开始, 结束时间*/
@property (nonatomic, strong) UILabel *labelForBeginTime;
@property (nonatomic, strong) UILabel *labelForEndTime;
@property (nonatomic, strong) UILabel *labelForAllTime;

// 菊花
@property (nonatomic,strong)SDP_ActivityIndicatorView *activityIndicatorView;

//// 播放
//@property (nonatomic,strong)UIButton *buttonForPlay;
// 暂停
@property (nonatomic,strong)UIButton *buttonForStop;

// 缓存条
@property (nonatomic,strong)UIView *sliderCatch;
// 高清
@property (nonatomic, strong)UIButton *buttonForHigh_definition;
// 标清
@property (nonatomic, strong)UIButton *buttonForSD;
@property (nonatomic, strong)UIButton *buttonForMark;
@property (nonatomic, strong)UIButton *buttonForShare;

//@property (nonatomic, strong)UIButton *buttonForNext;
@property (nonatomic, strong)UILabel *labelForMovieTitle;

@property (nonatomic, strong) KSBarrageView *barrageView;

@end

#define WIDTH  [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

@implementation SDP_ViewForAVPlayerWithUrl




// 播放器单例

+ (SDP_ViewForAVPlayerWithUrl *)shareVideoPlayer{
    
    static SDP_ViewForAVPlayerWithUrl *ViewPlayer = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        

    ViewPlayer = [[SDP_ViewForAVPlayerWithUrl alloc]initWithFrame:CGRectMake(0, 0, HEIGHT, WIDTH)];
        
    });
    
    return ViewPlayer;
}


// 视频主题 label 赋值

- (void)passMovieTitle: (NSString *)stringForMovieName{
    self.labelForMovieTitle.text = stringForMovieName;

}


/** 将网址传过来*/
- (void)passPlayerItemOfUrl:(NSString *)stringForURL{

   NSString *urlForPlayer = [stringForURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    // 创建视频项目对象
    self.moviePlayerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:urlForPlayer]];

    [self.moviePlayer replaceCurrentItemWithPlayerItem:self.moviePlayerItem];

    [self.moviePlayer play];
    
    


    // 添加菊花
    [self creatActivityIndicatorView];
    
    // 监听status属性, 视频加载好后,取消菊花
    [self creatObserverForStatus];
    
    
}


//URL:(NSURL *)url

- (instancetype)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];

    if (self) {
        
//        // 创建视频项目对象
//        self.moviePlayerItem = [[AVPlayerItem alloc] initWithURL:url];
        //创建视频播放器对象
        self.moviePlayer = [AVPlayer playerWithPlayerItem:self.moviePlayerItem];
        
        //创建承载播放器的AVPlayerLayer对象
        self.moviePlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.moviePlayer];

        self.moviePlayerLayer.backgroundColor = [UIColor blackColor].CGColor;
        //  视图播放器layer层视图大小
        self.userInteractionEnabled = YES;

        self.moviePlayerLayer.frame = frame;
        //视频填充模式
        self.moviePlayerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
        //将播放器添加到父视图的layer层上
        [self.layer insertSublayer:self.moviePlayerLayer atIndex:0];
        // 父视图的背景颜色
        self.backgroundColor = [UIColor blackColor];
        
        /** 开始播放*/
        [self.moviePlayer play];
    
        
        //创建播放按键
        [self creatPlayButton];

        
        // 创建slider 时间显示的 view
        [self  creatTimeWhithSliderViews];
        
        // 调用slider观察者
        [self addProgressObserver];
    
        /** 添加播放结束通知中心 */
        [self addNotificationCenters];
        
        
        //弹幕创建
        self.barrageView = [[KSBarrageView alloc] initWithFrame:frame];
        [self addSubview:self.barrageView];
        self.barrageView.userInteractionEnabled = NO;
        self.barrageView.backgroundColor = [UIColor clearColor];
        
        
    
    }
    return self;
}

// 获取弹幕数据
- (void)setDataArray:(NSArray *)arr {
    [self.barrageView setDataArray:arr];
    [self.barrageView start];
}

#pragma mark -- 创建底部 slider 和时间显示 视图

- (void)creatTimeWhithSliderViews{

    // 添加底部 view
    CGFloat height = WIDTH/8; // 进度条高度
    self.sliderView = [[UIView alloc]initWithFrame:CGRectMake(0, WIDTH - height, HEIGHT, WIDTH)];
    self.sliderView.backgroundColor = [UIColor clearColor];
    self.sliderView.hidden = YES;
    [self addSubview:self.sliderView];
    
    
    /** 返回 button */
    self.buttonForBack = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonForBack.frame = CGRectMake(HEIGHT/35, HEIGHT/40, WIDTH/15, WIDTH/15);
    [self.buttonForBack setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    self.buttonForBack.backgroundColor = [UIColor clearColor];
   
    [self addSubview:self.buttonForBack];
    self.buttonForBack.hidden = YES;
    
    
    /** 高清 标清 button*/
    self.buttonForHigh_definition = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonForHigh_definition.frame = CGRectMake(HEIGHT/1.4, WIDTH/60, WIDTH/10, WIDTH/10);
    [self.buttonForHigh_definition setImage:[UIImage imageNamed:@"Hight_definition"] forState:UIControlStateNormal];
    self.buttonForHigh_definition.backgroundColor = [UIColor clearColor];
    [self addSubview:self.buttonForHigh_definition];
    self.buttonForHigh_definition.hidden = YES;
    
    /** 收藏 button*/
     self.buttonForMark = [UIButton buttonWithType:UIButtonTypeCustom];
     self.buttonForMark.frame = CGRectMake(HEIGHT/1.24, WIDTH/30, WIDTH/15, WIDTH/15);
    [self.buttonForMark setImage:[UIImage imageNamed:@"mark"] forState:UIControlStateNormal];
    self.buttonForMark.backgroundColor = [UIColor clearColor];
    [self addSubview:self.buttonForMark];
    self.buttonForMark.hidden = YES;
    
    
    
    /** 分享 button*/
    self.buttonForShare = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonForShare.frame = CGRectMake(HEIGHT/1.14, WIDTH/30, WIDTH/15, WIDTH/15);
    [self.buttonForShare setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    self.self.buttonForShare.backgroundColor = [UIColor clearColor];
    [self addSubview:self.self.buttonForShare];
    self.buttonForShare.hidden = YES;
    
    //跳转到下一个视频
     self.buttonForNext = [UIButton buttonWithType:UIButtonTypeCustom];
     self.buttonForNext.frame = CGRectMake(HEIGHT/1.1, WIDTH/2 - WIDTH/10/2, WIDTH/10, WIDTH/10);
    [self.buttonForNext setImage:[UIImage imageNamed:@"next"] forState:UIControlStateNormal];
     self.buttonForNext.backgroundColor = [UIColor clearColor];
    
//    [self.buttonForNext addTarget:self action:@selector(replaceItems:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview: self.buttonForNext];
    self.buttonForNext.hidden = YES;

    
    
    /** slider滑块*/
    self.sliderForMovie = [[UISlider alloc] initWithFrame:CGRectMake(HEIGHT/9, HEIGHT/45, HEIGHT - HEIGHT/9*2, WIDTH/40)];
    
    [ self.sliderForMovie setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateNormal];
    
    /** slider 滑块方法 */
    [self.sliderForMovie addTarget:self action:@selector(ProgressAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 设置滑块左侧的颜色
    self.sliderForMovie.minimumTrackTintColor = [UIColor grayColor];
    
    // 右侧滑动条颜色
    self.sliderForMovie.maximumTrackTintColor = [UIColor darkGrayColor];
    [self.sliderView addSubview:self.sliderForMovie];
    
    
    // 添加进度label
    self.labelForBeginTime = [[UILabel alloc]initWithFrame:CGRectMake(HEIGHT/100,WIDTH/30, HEIGHT/10, WIDTH/30)];
    self.labelForBeginTime.backgroundColor = [UIColor clearColor];
    self.labelForBeginTime.textColor = [UIColor whiteColor];
    self.labelForBeginTime.textAlignment = NSTextAlignmentCenter;
    self.labelForBeginTime.text = @"00:00";
    [self.sliderView addSubview:self.labelForBeginTime];

    // 4.添加剩余时长label
    self.labelForEndTime = [[UILabel alloc]initWithFrame:CGRectMake(HEIGHT/1.12,WIDTH/30,HEIGHT/10, WIDTH/30)];
    self.labelForEndTime.backgroundColor = [UIColor clearColor];
    self.labelForEndTime.textColor = [UIColor whiteColor];
    self.labelForEndTime.textAlignment = NSTextAlignmentCenter;
    self.labelForEndTime.text = @"00:00";
    [self.sliderView addSubview:self.labelForEndTime];

    
    // 5. 添加平移滑动时时间的显示块 label
    
    self.labelForAllTime = [[UILabel alloc]initWithFrame:CGRectMake(HEIGHT/2 - self.bounds.size.width/4/2, HEIGHT/2.4, self.bounds.size.width/4, WIDTH/7)];
    self.labelForAllTime.font =[UIFont systemFontOfSize:17];
    self.labelForAllTime.backgroundColor = [UIColor clearColor];
    self.labelForAllTime.textColor = [UIColor whiteColor];
    self.labelForAllTime.textAlignment = NSTextAlignmentCenter;
    [self addSubview:self.labelForAllTime];
    self.labelForAllTime.hidden = YES;
    
    
    // 6. 添加音量的 slider
    
    
    self.sliderForVoice = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, WIDTH/2.8   , WIDTH/20)];
    self.sliderForVoice.center = CGPointMake(HEIGHT/20, WIDTH/2);
    self.sliderForVoice.backgroundColor = [UIColor clearColor];
    [self.sliderForVoice setThumbImage:[UIImage imageNamed:@"VoiceForSlider"] forState:UIControlStateNormal];
    self.sliderForVoice.transform = CGAffineTransformMakeRotation(M_PI * 1.5);
    [self addSubview:self.sliderForVoice];
    self.sliderForVoice.hidden = YES;
    
    
    // 视频主题 label
    
    self.labelForMovieTitle = [[UILabel alloc]initWithFrame:CGRectMake(HEIGHT/15, HEIGHT/40, HEIGHT/1.7, WIDTH/15)];
    self.labelForMovieTitle.backgroundColor = [UIColor clearColor];
    [self addSubview:self.labelForMovieTitle];
//    self.labelForMovieTitle.text = @"走过了美国西海岸和东海岸";
    self.labelForMovieTitle.font = [UIFont systemFontOfSize:14];
    self.labelForMovieTitle.textColor = [UIColor whiteColor];
    self.labelForMovieTitle.hidden = YES;
    
    /** 缓存条创建 */
    self.sliderCatch = [[UIView alloc] init];
    self.sliderCatch.backgroundColor = [UIColor whiteColor];


    
    // 创建两个UIImageView，用来展示音量的max，min图标
    CGFloat volumWidth = WIDTH/15; // 图标的高度
    UIImageView *maxImageView = [[UIImageView alloc]initWithFrame:CGRectMake(self.sliderForVoice.frame.size.height , 0, volumWidth, volumWidth)];
    maxImageView.backgroundColor = [UIColor clearColor];
    maxImageView.image = [UIImage imageNamed:@"maxVoice"];
    maxImageView.transform = CGAffineTransformMakeRotation(M_PI * 2.5);
    [self.sliderForVoice addSubview:maxImageView];
    
    UIImageView *minImageView = [[UIImageView alloc]initWithFrame:CGRectMake(- volumWidth, 0, volumWidth, volumWidth)];
    minImageView.image = [UIImage imageNamed:@"miniVoice"];
    minImageView.backgroundColor = [UIColor clearColor];
    minImageView.transform = CGAffineTransformMakeRotation(M_PI * 2.5);
    [self.sliderForVoice addSubview:minImageView];


}



#pragma mark --/** slider 拖动事件 */

- (void)ProgressAction:(UISlider *) slider{
    
    UISlider *sliderForTime = slider;
    
    //获取当前时间
    double currentTime = self.totalMovieDuration * sliderForTime.value;
    CMTime dragedCMTime = CMTimeMake(currentTime, 1);
    
    // 跳转视频
    [self.moviePlayer seekToTime:dragedCMTime completionHandler:^(BOOL finished) {

    }];
    
}





#pragma mark -  添加时间进度观察者 - addProgressObserver

- (void)addProgressObserver {
  
     __weak SDP_ViewForAVPlayerWithUrl *view = self;
    
    //设置(1,1) 设置每秒执行一次
    
    [view.moviePlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue: dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        //总时长 将CMTime类型转成float类型 持续时间总时长
        CGFloat duration = CMTimeGetSeconds(view.moviePlayerItem.duration);
        
        //当前时间, 实时
        CGFloat current = CMTimeGetSeconds(view.moviePlayer.currentTime);
        
        //倒计时 剩余时间
//        CGFloat rem = duration - current;
        
        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)duration/60 ,(int)duration%60];
        NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)current/60 ,(int)current%60];

        // 总时长和进度时间赋值
        view.labelForBeginTime.text = currenT ;
        // 也可以将时间变为总时长, 直接转换 duration 时间即可
        view.labelForEndTime.text = totalT;

        //保存总时长用于手动快进和快退
        view.totalMovieDuration = duration;

        //设置进度值 当前时间/总时长
        view.sliderForMovie.value = current/duration;
    }];
}





#pragma mark --  播放页面添加轻拍手势 隐藏控件 手势添加到整个 view, 相关控件点击进行隐藏显现

- (void)addGestureRecognizer {
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAllSubViews)];
    
    [self addGestureRecognizer:tap];
}

// 轻拍手势的方法

-(void)dismissAllSubViews {

    [self viewNoDismiss];
    self.buttonForPlay.hidden = !self.buttonForPlay.hidden;
    self.sliderView.hidden = !self.sliderView.hidden;
    self.sliderForVoice.hidden = !self.sliderForVoice.hidden;
    
    self.buttonForBack.hidden = !self.buttonForBack.hidden;
    self.buttonForHigh_definition.hidden = !self.buttonForHigh_definition.hidden;
    self.buttonForMark.hidden = !self.buttonForMark.hidden;
    self.buttonForShare.hidden = !self.buttonForShare.hidden;
    self.buttonForNext.hidden = !self.buttonForNext.hidden;
    self.labelForMovieTitle.hidden = !self.labelForMovieTitle.hidden;

}

#pragma mark - 保证视图不消失的方法,每次调用这个方法，把之前的倒计时抹去，添加一个新的3秒倒计时
- (void)viewNoDismiss
{
    // 先取消一个3秒后的方法，保证不管点击多少次，都只有一个方法在3秒后执行
    [UIView cancelPreviousPerformRequestsWithTarget:self selector:@selector(dismissAction) object:nil];
    
    // 3秒后执行的方法
    [self performSelector:@selector(dismissAction) withObject:nil afterDelay:3];
    
}

// 3秒后执行的方法
- (void)dismissAction
{
    self.buttonForPlay.hidden = YES;
    self.sliderView.hidden  = YES;
    self.sliderForVoice.hidden = YES;
    
    self.buttonForBack.hidden = YES;
    self.buttonForHigh_definition.hidden = YES;
    self.buttonForMark.hidden = YES;
    self.buttonForNext.hidden = YES;
    self.buttonForShare.hidden = YES;
    self.labelForMovieTitle.hidden = YES;
    
}

#pragma  mark --  监听status属性, 视频加载好后,取消菊花

- (void)creatObserverForStatus{

    // 播放器视频状态
    [self.moviePlayerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew  context:nil];
    
    //监控网络加载情况属性
    [self.moviePlayerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew  context:nil];
    
    // 监控 playbackBufferEmpty 缓冲为空
    [self.moviePlayerItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
    
    /// 当缓冲好的时候
     [self.moviePlayerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];

}



#pragma mark -  播放器视频状态

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    self.moviePlayerItem = (AVPlayerItem *)object;
    
    if ([keyPath isEqualToString:@"status"]) {
        
        // 视频准备好
        if ([self.moviePlayerItem status] == AVPlayerStatusReadyToPlay) {
           
            NSLog(@"AVPlayerStatusReadyToPlay");
            
            // 取消菊花动画
            [self.activityIndicatorView stopAnimating];
            
            //视频加载完后给视频添加手势
            [self addGestureRecognizer];

            // 添加平移手势，用来控制(音量)和快进快退
            UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panDirection:)];
            [self addGestureRecognizer:pan];

            
        } else if ([self.moviePlayerItem status] == AVPlayerStatusFailed) {
            NSLog(@"AVPlayerStatusFailed");
        }
        
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {

        NSArray *array=self.moviePlayerItem.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
#warning 缓冲打印
        // NSLog(@"共缓冲：%.2f",totalBuffer);
        
        
        //总时长 将CMTime类型转成float类型 持续时间总时长
        CMTime duration = self.moviePlayerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);

        // 调用缓存视图
        [self setCache:totalBuffer / totalDuration];

    }else if ([keyPath isEqualToString:@"playbackBufferEmpty"]) {
        
        // 当缓冲是空的时候
        if (self.moviePlayerItem.playbackBufferEmpty) {
          
            NSLog(@"我是:playbackBufferEmpty");
            
        }
        
    }else if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"]) {
        
        // 当缓冲好的时候
        if (self.moviePlayerItem.playbackLikelyToKeepUp){
#warning 当缓冲好的时候
            //NSLog(@"playbackLikelyToKeepUp");
            
        }
        
    }

}


#pragma mark - 缓存控制缓存 view 的fram (X 值)

- (void)setCache:(CGFloat)cache
{
    
    if (cache < self.sliderForMovie.minimumValue) {
        cache = self.sliderForMovie.minimumValue;
    }
    else if (cache > self.sliderForMovie.maximumValue){
        cache = self.sliderForMovie.maximumValue;
    }
    
    /** 求出百分比*/
    CGFloat progress = cache / (self.sliderForMovie.maximumValue - self.sliderForMovie.minimumValue);

    // 对cacheView的frame进行赋值

        CGFloat thumbX = self.sliderCatch.frame.origin.x; // 滑块的x值
        self.sliderCatch.frame = CGRectMake(thumbX , WIDTH/160, progress * self.sliderForMovie.frame.size.width - thumbX, 2);
        [self.sliderForMovie addSubview:self.sliderCatch];
 
}


#pragma mark --  获取系统音量

- (void)configureVolume:(CGFloat) value
{
    
    // 更改系统的音量,比数越小幅度越小
    self.sliderForVoice.value  -= value / 10000;

    NSArray *audioTracks = [self.moviePlayerItem.asset tracksWithMediaType:AVMediaTypeAudio];
    NSMutableArray *allAudioParams = [NSMutableArray array];
    for (AVAssetTrack *track in audioTracks) {
        AVMutableAudioMixInputParameters *audioInputParams =
        [AVMutableAudioMixInputParameters audioMixInputParameters];
        [audioInputParams setVolume:self.sliderForVoice.value atTime:kCMTimeZero];
        [audioInputParams setTrackID:[track trackID]];
        [allAudioParams addObject:audioInputParams];
    }
    
    AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
    [audioMix setInputParameters:allAudioParams];
    
    [self.moviePlayerItem setAudioMix:audioMix];
        

}

#pragma mark -- 平移手势方法

- (void)panDirection:(UIPanGestureRecognizer *)pan{
    
    
    CGPoint velocityPoint = [pan velocityInView:self];
    
    switch (pan.state) {
            
        case UIGestureRecognizerStateBegan:{
            
            CGFloat x = fabs(velocityPoint.x);
            CGFloat y = fabs(velocityPoint.y);
            
            /**水平方向滑动*/
            
            if (x > y) {
                
                panDirection = PanDirectionHorizontalMoved;
                
                // 取消隐藏
                self.labelForAllTime.hidden = NO;
                
                // 给sumTime初值, 当前时间(拖动显示时间)
                sumTime = CMTimeGetSeconds(self.moviePlayer.currentTime);
                
                // 滑动的时候选择状态变为 NO, 如果状态不进行更改,点击暂停后再拖动,选择状态将不会改变,这里点击暂停后,拖动后视频状态应该为播放状态; 判断是否为播放状态,如果为1为正常播放状态,将button状态改为 播放状态,反之为暂停状态
                if (self.moviePlayer.rate == 1) {
                    self.buttonForPlay.selected = NO;
                    
                }else{

                    self.buttonForPlay.selected = YES;

                }
                
                
            }else if (x < y){
            
                NSLog(@"垂直滑动");
                
                panDirection = PanDirectionVerticalMoved;
                // 显示音量控件
                self.sliderForVoice.hidden = NO;
                // 开始滑动的时候，状态改为正在控制音量
                isVolume = YES;

            
            }
            
            break;
            
        }
        // 正在移动
        case UIGestureRecognizerStateChanged:{
            
            switch (panDirection) {
                case PanDirectionHorizontalMoved:{
                    
                    // 水平移动的方法只要x方向的值
                    [self horizontalMoved:velocityPoint.x];
                    break;
                }
                case PanDirectionVerticalMoved:{
                    
                    // 音量调节方法(滑动)
                    [self  configureVolume:velocityPoint.y];
                    
                    break;
                }
                default:
                    break;
            }
            break;
        }
            // 移动停止
        case UIGestureRecognizerStateEnded:{
            
            // 移动结束也需要判断垂直或者平移
            // 比如水平移动结束时，要快进到指定位置，如果这里没有判断，当我们调节音量完之后，会出现屏幕跳动的bug
            switch (panDirection) {
                case PanDirectionHorizontalMoved:{
                    
                    
                    /** 延迟两秒 快进栏消失*/
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
                        
                        // 隐藏快进快退视图
                        self.labelForAllTime.hidden = YES;
                    });

                    /** 滑动后,视频跳转, sumTime 为拖动后总的的时长*/
                    CMTime dragedCMTime = CMTimeMake(sumTime, 1);
                    
                    __weak SDP_ViewForAVPlayerWithUrl *weakSelf = self;
                    [self.moviePlayer seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
                        
                        //根据播放的状态,判断,滑动后视频是否为播放还是暂停,如果为1 正在播放状态,让视频依然播放, 如果是暂停状态快进快退,视频为暂停状态
                        
                        if (weakSelf.moviePlayer.rate == 1) {
                            
                            [weakSelf.moviePlayer play];
                        }else{
                        
                            
                             [weakSelf.moviePlayer pause];
                        }

                    }];

                    // 把sumTime滞空，不然会越加越多
                    sumTime = 0;
                    break;
                }
                case PanDirectionVerticalMoved:{

                    
                     self.sliderForVoice.hidden = YES;
                    // 把状态改为不再控制音量
                    isVolume = NO;
                    
                    break;
                }
                default:
                    break;
            }
            break;
        }
  
            
        default:
            break;
    }
    
}

#pragma mark - pan水平移动的方法 ( 快进, 快退 )
    
- (void)horizontalMoved:(CGFloat)value{
    
    
    // 快进快退的方法
    NSString *style = @"";
    
    if (value < 0) {
        style = @"<<";
    }
    else if (value > 0){
        style = @">>";
    }
    
    
    // 每次滑动需要叠加时间 除数为 快进速率(越小 滑动随时间越短 快进越多)
    sumTime += value / 200;
    
    // 需要限定sumTime的范围
    if (sumTime >  self.totalMovieDuration) {
        sumTime =  self.totalMovieDuration;
    }else if (sumTime < 0){
        sumTime = 0;
    }

    
    //总时长 将CMTime类型转成float类型 持续时间总时长
    CGFloat duration = CMTimeGetSeconds(self.moviePlayerItem.duration);
    
    // 将float转换分钟秒
    NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)duration/60 ,(int)duration%60];
    //当前时间, 实时
    CGFloat current = sumTime;
    NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)current/60 ,(int)current%60];
    // 进度时间/ 视频总时长
    NSString *timeStr = [NSString stringWithFormat:@"%@ %@/%@",style,currenT,totalT];
    self.labelForAllTime.text =  timeStr;
    

    }







#pragma mark - 观察者 观察播放完毕 观察屏幕旋转
- (void)addNotificationCenters {
    
    //  注册观察者用来观察，是否播放完毕  AVPlayerItemDidPlayToEndTimeNotification 该通知的对象是播放完毕的项目。
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

#pragma mark 播放结束后的代理回调
- (void)moviePlayDidEnd:(NSNotification *)notify {
    
// 播放到最开始暂停
    
    NSLog(@"播放结束触发");
    
    CMTime dragedCMTime = CMTimeMake(0, 1);
    
    
    __weak SDP_ViewForAVPlayerWithUrl *weakSelf = self;
    [self.moviePlayer seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
        
        [weakSelf.moviePlayer pause];
        
        // 播放到开始, 播放按键变为暂停状态
        weakSelf.buttonForPlay.selected = YES;
        
    }];
    
    
}


#pragma mark -- 创建播放 button 点击事件

- (void)creatPlayButton{
    
    // 播放 button
    
    self.buttonForPlay = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonForPlay.frame = CGRectMake(WIDTH/2, HEIGHT/2, HEIGHT/10, HEIGHT/10);
    self.buttonForPlay.center = self.center;
    [self.buttonForPlay setImage:[UIImage imageNamed:@"play"] forState:UIControlStateSelected];
    [self.buttonForPlay setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
    self.buttonForPlay.backgroundColor = [UIColor clearColor];
    
    // 开始 button 隐藏
    self.buttonForPlay.hidden = YES;
    
    //添加暂停播放方法
    [self.buttonForPlay addTarget:self action:@selector(playMovieAction:) forControlEvents:UIControlEventTouchUpInside];

    // 添加播放按键到视图
    [self addSubview:self.buttonForPlay];

}







#pragma mark  -- 添加菊花动画 ( 重写菊花视图方法封装 )

- (void)creatActivityIndicatorView{
    
    self.activityIndicatorView = [[SDP_ActivityIndicatorView alloc] initWithFrame:CGRectMake(HEIGHT/2-50,HEIGHT/2-50, 100, 100)];
    self.activityIndicatorView.center = self.center;
    [self addSubview:self.activityIndicatorView];
    [self.activityIndicatorView startAnimating];

}



#pragma mark - 播放暂停方法
- (void)playMovieAction:(UIButton *)button
{
    button.selected = !button.selected;
    if (button.selected) {
        // 暂停
        [self.moviePlayer pause];

    }else{
        // 播放
        [self.moviePlayer play];
    }
    
}








#pragma mark -- 切换视频


//- (void)replaceItems:(UIButton *)button{
//
//    //切换视频
////    [self.moviePlayerLayer replaceCurrentItemWithPlayerItem:[];
////   
//
//
//}









@end
